package com.china08.yxyapi.api.manage.tec.teaching.homework.workassign;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.homework.HomeworkTask;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.security.profile.YxyProfile;
import com.china08.yxyapi.service.manage.tec.teaching.homework.WorkAssignService;
import com.china08.yxyapi.util.JpushForMessageUtil;
import com.china08.yxyapi.util.JpushForNotificationUtil;
import com.china08.yxyapi.util.YxUserPointsUtilV3;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * 老师---发布作业
 * 
 */
@Api(tags = { "V02", "作业系统" })
@CrossOrigin
@RestController
public class WorkAssignQuesCrtV2Controller extends YxyApiBaseController {

    @Autowired
    private WorkAssignService workAssignService;

    @Autowired
    private YxUserPointsUtilV3 yxUserPointsUtilV3;

    @ApiOperation(value = "作业系统老师发布作业")
    @RequestMapping(value = "/api_yw/manage/tec/homework/workassign/ques/crt.v2", method = RequestMethod.POST)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModelV2 reqModel)
            throws ParseException {

        YxyProfile yxyProfile = getProfile(request, response);
        String schoolId = yxyProfile.getSchoolId();
        String userId = yxyProfile.getId();
        String userNick = yxyProfile.getUserNick();
        RespModel respModel = new RespModel();
        HomeworkTask sendHomeWork = workAssignService.sendHomeWorkV2(reqModel, schoolId, userId, userNick);
        respModel.setMessage("发布作业成功");

        // 加积分
        yxUserPointsUtilV3.sendHomework(userId);

        // 当前时间延迟20秒
        Date pubDate = sendHomeWork.getPublishDate();
        Date curDate = new Date();

        Calendar dateOne = Calendar.getInstance();
        dateOne.setTime(pubDate);

        Calendar dateTwo = Calendar.getInstance();
        dateTwo.setTime(curDate);

        long timeOne = dateOne.getTimeInMillis();
        long timeTwo = dateTwo.getTimeInMillis();
        long minute = (timeOne - timeTwo) / (1000 * 60);

        Date time = null;
        if (minute > 3) {
            time = sendHomeWork.getPublishDate();
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sendHomeWork.getPublishDate());
            calendar.add(Calendar.SECOND, 20);
            time = calendar.getTime();
        }

        // 定时推送作业
        List<String> tabAndList = new ArrayList<>();
        tabAndList.add("PARENTS" + schoolId);
        List<String> allParentIdList = new ArrayList<String>();
        List<String> allStudentIdList = new ArrayList<String>();
        List<ClassModelV2> classModelList = reqModel.classModelList;
        for (ClassModelV2 classModel : classModelList) {
            List<StudentModelV2> studentModelList = classModel.studentModelList;
            for (StudentModelV2 studentModel : studentModelList) {
                allParentIdList.addAll(studentModel.parentIds);
                allStudentIdList.add(studentModel.studentId);

                List<String> parentIdList = new ArrayList<String>();
                parentIdList.addAll(studentModel.parentIds);
                // app端----定时推送作业
                Map<String, String> map = new HashMap<String, String>();
                map.put("modelId", "homeworkNotice");
                JpushForNotificationUtil.sendNotificationTiming(
                        "您的孩子（" + studentModel.studentName + "）有一份" + reqModel.subjectName + "作业", "班级作业", map,
                        parentIdList, tabAndList, time);

                // 电子书包----定时推送作业
                JpushForNotificationUtil.sendNotificationPack(
                        "您的孩子（" + studentModel.studentName + "）有一份" + reqModel.subjectName + "作业", "班级作业", map,
                        parentIdList, null, time);
            }
        }
        List<String> allParentIdList1 = new ArrayList<String>(new TreeSet<String>(allParentIdList));
        // message
        List<Integer> roleIdList = new ArrayList<>();
        roleIdList.add(1);
        JpushForMessageUtil.sendMessageTiming(8, roleIdList, schoolId, allParentIdList1, tabAndList, time);
        return respModel;
    }

    public static class ReqModelV2 extends YxyApiReqModel {

        // 学段
        public String stage;

        // 学科
        public String subject;

        // 学科名称
        public String subjectName;

        // 作业名称
        public String title;

        // 通知类作业内容
        public String content;

        // 试题list
        public List<QuesModelV2> quesIdList;

        // 知识点ids
        public List<Integer> knowIdList;

        // 知识点名称
        public List<String> knowNameList;

        // 通知类作业的图片
        public List<ArticleModelV2> quesImages;

        // 通知类作业的文档
        public List<ArticleModelV2> quesArticles;

        // 发布的班级列表
        public List<ClassModelV2> classModelList;

        // 作业开始时间
        public String startDate;

        // 作业立即开始 2立即开始 1自定义时间
        public Integer type1;

        // 作业的截止时间
        public String endDate;

        // 作业的截止类型 3今晚 6明晚 9本周末
        public Integer type2;

        // 公布答案的类型
        public Integer publishAnswer;

        // 是否需要学生在线提交作业
        public Boolean ifNeedSumbit;

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(title, null), "请输入作业名称");
            Assert.isTrue(!CollectionUtils.isEmpty(classModelList), "请选择班级");
        }
    }

    public static class QuesModelV2 {
        // 题的id
        public String quesId;
        // 题涉及的知识点ids
        public List<Integer> know;

        public String getQuesId() {
            return quesId;
        }

        public void setQuesId(String quesId) {
            this.quesId = quesId;
        }

        public List<Integer> getKnow() {
            return know;
        }

        public void setKnow(List<Integer> know) {
            this.know = know;
        }

    }

    public static class ArticleModelV2 {

        // 文档名称
        public String docName;

        // 文档路径
        public String docUrl;

    }

    public static class ClassModelV2 {
        // 班级id
        public String classId;
        // 班级名称
        public String classNick;
        // 年级
        public String grade;
        // 学生数量
        public Integer studentNum;
        // 班级里学生
        public List<StudentModelV2> studentModelList;
    }

    public static class StudentModelV2 {
        // 学生id
        public String studentId;
        // 学生姓名
        public String studentName;
        // 学生头像
        public String avatar;
        // 家长ids
        public List<String> parentIds;
    }

    protected static class RespModel extends YxyApiRespModel {

    }

}
